﻿Imports System.Windows.Data

''' <summary>
''' 
''' </summary>
''' <remarks></remarks>
Public Class MultiSelectionConverter
    Implements IValueConverter

    Private Class Wrapper

        Dim _Selected As Boolean
        Dim _owner As VMParametrageElement

        Sub New(ByVal obj As Object, ByVal owner As VMParametrageElement)
            Source = obj
            Me._owner = owner
        End Sub
        Sub New(ByVal obj As Object, ByVal owner As VMParametrageElement, ByVal selected As Boolean)
            Source = obj
            Me._owner = owner
            Me._Selected = selected
        End Sub
        Public Property Source As Object
        Public Property Selected As Boolean
            Get
                Return _Selected
            End Get
            Set(ByVal value As Boolean)
                If value <> _Selected Then
                    _Selected = value
                    If _Selected Then
                        If _owner.Value Is Nothing Then
                            _owner.Value = New List(Of Object)
                        End If
                        _owner.Value.Add(Source)
                    Else
                        If _owner.Value IsNot Nothing Then
                            _owner.Value.Remove(Source)
                        End If
                    End If
                End If
            End Set
        End Property
    End Class


    Private Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Try
            Dim elt As VMParametrageElement = value
            Dim all As IEnumerable(Of Object) = TryCast(elt.EditorOptions, IEnumerable).Cast(Of Object)()
            Dim sel As IList = TryCast(elt.Value, IList)

            If sel Is Nothing Then Return all.Select(Function(obj) New Wrapper(obj, elt))

            Return all.Select(Function(obj) New Wrapper(obj, elt, sel.Contains(obj)))
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

    Private Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException()
    End Function
End Class